<template>
  <div>
    <div class="all">
      <div class="headers">
        <el-tabs style="width:100%">
            <div class="tagtable">
              <div style="background:#fff;padding:20px">
                <div style="display:flex;  justify-content: space-between;align-items: center;">
                  <div style="width:100%">
                    <el-form :inline="true" ref="form" :model="form">
                      <el-form-item>
                        <el-button type="success" @click="addMachine">新增设备</el-button>
                      </el-form-item></br>
                        <!-- 查询表单 -->
                      <el-form-item label="设备名称："> 
                        <el-input v-model="form.equipmentName" placeholder="请输入门名称"></el-input>
                      </el-form-item>
                      <el-form-item label="SN编号："> 
                        <el-input v-model="form.equipmentNo" placeholder="请输入SN编号"></el-input>
                      </el-form-item>
                      <el-form-item label="商户名称："> 
                        <el-input v-model="form.mchName" placeholder="请输入商户名称"></el-input>
                      </el-form-item>
                      <el-form-item label="门店名称："> 
                        <el-input v-model="form.storeName" placeholder="请输入门店名称"></el-input>
                      </el-form-item>
                      <el-form-item label="在线状态：">
                        <el-select v-model="form.status" placeholder="请选择" clearable style="width:8vw;">
                          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="是否启用：">
                        <el-select v-model="form.enableStatus" placeholder="请选择" clearable style="width:8vw;">
                          <el-option v-for="item in storetag" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                        </el-select>
                      </el-form-item>
                      <el-button type="primary" @click="equipment">查询</el-button>
                      <el-button icon="el-icon-refresh-left" @click="reset">重置</el-button>
                    </el-form>
                  </div>
                </div>
                <!-- 设备列表 -->
                <el-table class="alldata" :data="tableData" stripe  style="width: 100%;margin-top:20px;overflow: auto;" :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
                  <el-table-column type="index" label="序号" align="center" > 
                    <template scope="scope"><span>{{scope.$index+(form.pageNum - 1) * form.pageSize + 1}} </span></template>
                  </el-table-column>
                  <el-table-column prop="equipmentNo" label="SN编号" align="center" > </el-table-column>
                  <el-table-column prop="equipmentName" label="设备名称" align="center"> </el-table-column>
                  <el-table-column prop="userCount" label="绑定人数" align="center"> </el-table-column>
                  <el-table-column prop="status" label="设备在线状态" align="center">
                    <template slot-scope="scope">
                      <span v-if="scope.row.status == 0">在线</span>
                      <span v-else>离线</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="mchName" label="商户名称" align="center"> </el-table-column>
                  <el-table-column prop="mchId" label="商户编码" align="center"> </el-table-column>
                  <el-table-column prop="storeName" label="门店名称" align="center"> </el-table-column>
                  <el-table-column prop="storeId" label="门店编码" align="center"></el-table-column>
                  <el-table-column prop="enableStatus" label="是否启用" align="center">
                    <template slot-scope="scope">
                      <el-switch class="lef" v-model="scope.row.enableStatus == 0 ? true : false" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column prop="activationTime" label="激活时间" align="center"></el-table-column>
                  <el-table-column label="操作" width="300" align="center">
                    <template slot-scope="scope">
                      <el-button size="mini" @click="addUnfasten(scope.row)">加绑</el-button>
                      <el-button size="mini" type="primary" @click="BindingDevice(scope.row)">修改门店</el-button>
                      <el-button size="mini" @click="unfasten(scope.row)">解绑</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <el-pagination class="fy" :page-sizes="[10, 50, 100, 200]" background :current-page="form.pageNum" :page-size="form.pageSize"  layout="total, sizes, prev, pager, next, jumper" 
            :total="pagecount" @current-change="paging" @size-change="handleSizeChange"> </el-pagination>
        </el-tabs>
      </div>
    </div>

    <!-- 新增设备弹窗 -->
    <el-dialog title="新增设备" :visible.sync="dialogFormVisible" width="40%" :center=true>
        <el-form :model="addform"  :rules="rules" ref="ruleForm">
            <el-form-item label="设备名称：" :label-width="formLabelWidth" prop="equipmentName">
                <el-input v-model="addform.equipmentName" style="width:90% !important;" autocomplete="off" placeholder="请选择设备名称"></el-input>
            </el-form-item>
            <el-form-item label="SN编号：" :label-width="formLabelWidth"  prop="equipmentNo">
                <el-input v-model="addform.equipmentNo" style="width:90% !important;" placeholder="请选择SN编号"></el-input>
            </el-form-item>

            <el-form-item label="所属商户：" :label-width="formLabelWidth" v-if="$store.state.user.userRole != 0">
              <el-input v-model="JSON.parse(this.$store.getters.userInfo).name" style="width:90% !important;"></el-input>
            </el-form-item>
            <el-form-item label="所属商户：" prop="mchId" class="phones" v-else :label-width="formLabelWidth"> 
              <el-select v-model="addform.mchId" placeholder="请选择" clearable class="select" style="width:90% !important;" value-key="id" @change="selectMerchantId">
                <el-option v-for="item in merchant" :key="item.id" :label="item.mchName" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属门店：" :label-width="formLabelWidth" prop="storeId">
                <el-select v-model="addform.storeId" placeholder="请选择门店编码" v-if="$store.state.user.userRole != 0" clearable style="width:90% !important;">
                    <el-option v-for="item in ShopsData" :key="item.id" :label="item.storeName" :value="item.id"> </el-option>
                </el-select>
                <el-select v-model="addform.storeId" placeholder="请选择门店编码" v-else :disabled="!(addform.mchId)" clearable style="width:90% !important;" @blur="storeNamechantId">
                    <el-option v-for="item in ShopsData" :key="item.id" :label="item.storeName" :value="item.id"> </el-option>
                </el-select>
            </el-form-item>
          
            <el-form-item label="是否启用：" :label-width="formLabelWidth" prop="enableStatus">
                <el-switch v-model="delivery" active-color="#13ce66" inactive-color="#DCDFE6"></el-switch>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmation('ruleForm')">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 修改门店的弹窗 -->
      <el-dialog title="修改门店" :visible.sync="mchdialogFormVisible" width="55%">
        <el-form  style="display:flex;justify-content: space-between;" class="editMch">
            <el-form-item label="商户名称：">
                <el-select v-model="storeParameter.mchName" placeholder="请选择商户名称" style="display: inline-block !important;">
                    <el-option v-for="item in merchant" :key="item.id" :label="item.mchName" :value="item.mchName"> </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="门店名称：">
                <el-select v-model="storeParameter.storeName" placeholder="请选择门店名称" clearable style="display: inline-block !important;">
                    <el-option v-for="item in ShopsData" :key="item.id" :label="item.storeName" :value="item.storeName"> </el-option>
                </el-select>
            </el-form-item>
            <el-form-item >
              <el-button type="primary" @click="shopMethod(storeParameter)">查 询</el-button>
            </el-form-item>
        </el-form>
          <el-table class="alldata" :data="ShopsData" stripe  style="width: 100%;overflow: auto;" :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
            <el-table-column width="50">
              <template scope="scope"> <el-checkbox v-model="checked" @change="checkedChange(scope.row)"></el-checkbox></template>
            </el-table-column>
            <el-table-column type="index" label="序号" align="center"> 
              <template scope="scope"><span>{{scope.$index+(form.pageNum - 1) * form.pageSize + 1}} </span></template>
            </el-table-column>
            <el-table-column prop="mchId" label="商户编码" align="center"> </el-table-column>
            <el-table-column prop="mchName" label="商户名称" align="center"> </el-table-column>
            <el-table-column prop="id" label="门店ID" align="center"> </el-table-column>
            <el-table-column prop="storeName" label="门店名称" align="center"></el-table-column>
            <el-table-column prop="storeImg" label="门店图片" align="center">
              <template slot-scope="scope">
                <img :src="'https://yswl-cloud-service.obs.cn-north-4.myhuaweicloud.com/'+scope.row.storeImg" alt="" width="80" height="80"/>
              </template>
            </el-table-column>
            <el-table-column prop="contactPhone" label="联系电话" align="center"> </el-table-column>
          </el-table>
            <el-pagination class="fy" :page-sizes="[10, 50, 100, 200]" background :page-size="storeParameter.pageSize"  layout="total, sizes, prev, pager, next, jumper" 
            :total="totalNum" @current-change="storePaging" @size-change="storeSizeChange" :current-page="storeParameter.pageNum"> </el-pagination>
        <div slot="footer" class="dialog-footer">
            <el-button @click="mchdialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="Confirm">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 解绑的弹窗 -->
      <el-dialog title="" :visible.sync="unbundleFormVisible" width="30%" :center=true>
        <div class="dialogUnbundle">
          您是否确定进行解绑</br>解绑后门店用户将更换从属关系
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="unbundleFormVisible = false">取 消</el-button>
            <el-button type="primary" @click=" unfastenConfirm">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 加绑 -->
    <el-dialog title="绑定门店" :visible.sync="addUnbundleFormVisible" width="20%" :center=true>
        <el-form :model="setShop">
            <el-form-item label="所属商户：" :label-width="formLabelWidth" v-if="$store.state.user.userRole != 0">
              <el-input v-model="JSON.parse(this.$store.getters.userInfo).name" style="width:90% !important;"></el-input>
            </el-form-item>
            <el-form-item label="所属商户：" prop="mchId" class="phones" v-else :label-width="formLabelWidth"> 
              <el-select v-model="setform.mchId" placeholder="请选择" clearable class="select" style="width:90% !important;" value-key="id" @change="selectMerchantId">
                <el-option v-for="item in merchant" :key="item.id" :label="item.mchName" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属门店：" :label-width="formLabelWidth" prop="storeId">
                <el-select v-model="setform.storeId" placeholder="请选择门店编码" v-if="$store.state.user.userRole != 0" clearable style="width:90% !important;">
                    <el-option v-for="item in ShopsData" :key="item.id" :label="item.storeName" :value="item.id"> </el-option>
                </el-select>
                <el-select v-model="setform.storeId" placeholder="请选择门店编码" v-else :disabled="!(setform.mchId)" clearable style="width:90% !important;" @blur="storeNamechantId">
                    <el-option v-for="item in ShopsData" :key="item.id" :label="item.storeName" :value="item.id"> </el-option>
                </el-select>
            </el-form-item>
          <!-- <el-form-item label="门店编码：" :label-width="formLabelWidth"  prop="ShopsValue">
            <el-input v-model="setShop.id" autocomplete="off"  placeholder="请选择门店名称"  style="width:80% !important;"></el-input>
          </el-form-item> -->
          <el-form-item label="是否启用：" :label-width="formLabelWidth">
            <el-switch v-model="switchValue" active-color="#13ce66" inactive-color="#DCDFE6"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addUnbundleFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUnfastenConfirm">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { deviceMerchabt, getMerchantList, shopMerchabt, equipmentMerchabt, compileShopMerchabt, UnlinkShopMerchabt } from '@/api/merchants'
import { myMixin } from '@/layout/mixin/ResizeHandler'

export default {
  mixins: [myMixin],
  data() {
    return {
      unfasenDevice : {//解绑参数
        id:null,//设备id
        storeId:null,//店铺id   商户解绑店铺设备必填
        mchId:null//商户id  平台解绑商户设备必填
      },
      switchValue: true,
      delivery: false,
      setShop: {
        //更改门店参数
        id: '', //店铺ID
        status: null, //绑定状态 0 已绑定 1未绑定
      },
      checked: false,
      totalNum: '', //门店列表分页总条数
      storeParameter: {
        //门店列表参数
        mchName: null, //商户名
        storeName: null, //店铺名
        pageNum: 1,
        pageSize: 10,
        mchId: JSON.parse(this.$store.getters.userInfo).mchId ? JSON.parse(this.$store.getters.userInfo).mchId : null, //商户id
      },
      addform: {
        //新增参数
        mchId: this.$store.state.user.userRole == 0 ? null : JSON.parse(this.$store.getters.userInfo).mchId, //商户id
        storeId: null,
        equipmentName: '', //设备名称
        equipmentNo: '', //设备SN编号
        activationTime: '', //激活时间
        enableStatus: null, //启用状态：0启用，1禁用
        mchType: this.$store.state.user.userRole,
        // creatorId:JSON.parse(this.$store.state.user.userInfo).id,//创建人id
      },
      setform: {
        //加绑参数
        mchId: this.$store.state.user.userRole == 0 ? null : JSON.parse(this.$store.getters.userInfo).mchId, //商户id
        storeId: null,
        equipmentName: '', //设备名称
        equipmentNo: '', //设备SN编号
        enableStatus: null, //启用状态：0启用，1禁用
        mchType: this.$store.state.user.userRole,
        // creatorId:JSON.parse(this.$store.state.user.userInfo).id,//创建人id
      },
      mchNameId: '', //所属商户里的商户名
      storeNameId: '', //所属门店里的门店名
      merchant: [], //所属商户数据
      ShopsData: [], //所属门店数据
      formLabelWidth: '120px',
      dialogFormVisible: false, //新增设备弹窗弹窗开关
      mchdialogFormVisible: false, //修改门店弹窗开关
      unbundleFormVisible: false, //解绑弹窗开关
      addUnbundleFormVisible: false, //加绑弹窗开关
      pagecount: 0, //总共多少条数据
      form: {
        //设备列表、查询参数
        equipmentName: null, //设备名称
        equipmentNo: null, //设备编号
        mchName: null, //商户名
        storeName: null, //店铺名
        status: null, //在线状态
        enableStatus: null, //启用状态：0启用，1禁用
        pageNum: 1,
        pageSize: 10,
        mchId: this.$store.getters.userInfo ? JSON.parse(this.$store.getters.userInfo).mchId : '1',
      },
      rules: {
        equipmentName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        equipmentNo: [{ required: true, message: '请输入SN编码', trigger: 'blur' }],
        // enableStatus:[{ required: true, message: '请选择是否启用', trigger: 'change' }],
        mchId: [{ required: true, message: '请选择商户', trigger: 'change' }],
        storeId: [{ required: true, message: '请选择门店', trigger: 'change' }],
      }, //表单验证数据
      tableData: [], //设备数据
      storetag: [
        { value: '0', label: '否' },
        { value: '1', label: '是' },
      ],
      options: [
        { value: '0', label: '在线' },
        { value: '1', label: '离线' },
      ],
    }
  },
  computed: {},
  created() {
    this.addform.activationTime = this.getNowFormatDate() //转换时间格式
    this.equipment()
    this.merchantsList()
    if (this.$store.state.user.userRole != 0) {
      console.log(this.storeParameter)
      this.shopMethod(this.storeParameter)
    }
  },
  methods: {
    confirmation(formName) {
      //新增设备

      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addshopMethod()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async addshopMethod() {//设备新增
      if (this.delivery) {
        this.addform.enableStatus = 0
      } else {
        this.addform.enableStatus = 1
      }
      let addshopRes = await equipmentMerchabt(this.addform)
      if (addshopRes.code == 200) {
        this.dialogFormVisible = false
        this.$message.success('新增成功！')
        location.reload()
      }
    },
    BindingDevice(id) {
      //修改门店打开弹窗
      console.log(this.storeParameter)
      this.shopMethod(this.storeParameter)
      this.mchdialogFormVisible = true
    },
    async Confirm() {
      //修改门店
      let res = await compileShopMerchabt(this.setShop)
      if (res.code == 200) {
        this.mchdialogFormVisible = false
        if (this.setShop.id) {
          this.addUnbundleFormVisible = false
        }
      }
    },
    unfasten(item) {
      //解绑打开弹窗
      this.unbundleFormVisible = true
      this.unfasenDevice.id = item.id
      if(this.$store.state.user.userRole == 0) {
        this.unfasenDevice.mchId = this.$store.getters.userInfo ? JSON.parse(this.$store.getters.userInfo).mchId : null
      }else{
        this.unfasenDevice.storeId = item.storeId
      }
    },
    async unfastenConfirm() {
      //解绑
      let res = await UnlinkShopMerchabt(this.unfasenDevice)
      if (res.code == 200) {
        this.unbundleFormVisible = false
        this.$message.success('解绑成功！')
        location.reload()
      }
    },
    addUnfasten(val) {
      //加绑打开弹窗
      this.addUnbundleFormVisible = true
      this.setform.equipmentName = val.equipmentName
      this.setform.equipmentNo = val.equipmentNo
      this.setform.enableStatus = val.enableStatus
      // this.addform.storeId = val.storeId
    },
    async addUnfastenConfirm() {
      //加绑
      this.setform.enableStatus = this.switchValue ? 0 : 1
      let res = await equipmentMerchabt(this.setform)
      if (res.code == 200) {
        this.addUnbundleFormVisible = false
        this.$message.success('绑定成功！')
        location.reload()
      }
    },
    async equipment() {
      //获取设备列表
      let res = await deviceMerchabt(this.form)
      if (res.code == 200) {
        this.tableData = res.data.list
        this.pageSize = res.data.pageSize
        this.pagecount = res.data.total
      }
    },
    reset() {
      //重置
      this.form.equipmentName = null
      this.form.equipmentNo = null
      this.form.mchName = null
      this.form.storeName = null
      this.form.status = null
      this.form.enableStatus = null
      this.equipment()
    },
    async merchantsList() {
      //获取商户数据
      let merRes = await getMerchantList()
      if (merRes.code == 200) {
        this.merchant = merRes.data.list
      }
    },
    async shopMethod(option) {
      console.log(option)
      //获取门店数据
      let shopRes = await shopMerchabt(option)
      if (shopRes.code == 200) {
        this.ShopsData = shopRes.data.list
        this.storeParameter.pageSize = shopRes.data.pageSize
        this.totalNum = shopRes.data.total
      }
    },
    selectMerchantId(val) {
      //所属商户ID选择触发
      let getShop = {}
      getShop.pageNum = 1
      getShop.pageSize = 100
      ;(getShop.mchId = this.$store.state.user.userRole == 0 ? val : JSON.parse(this.$store.getters.userInfo).mchId), //商户id
        this.shopMethod(getShop)
    },
    storeNamechantId(val) {
      //所属门店ID选择触发
      if (!this.ShopsData.length) {
        this.$message.error('该商户下没有店铺,请新建店铺！')
      }
    },
    paging(val) {
      //分页操作
      this.form.pageNum = val
      this.equipment()
    },
    handleSizeChange(val) {
      this.form.pageSize = val
      this.form.equipment()
    },
    storePaging(val) {
      //门店列表分页操作
      this.storeParameter.pageNum = val
      this.shopMethod()
    },
    storeSizeChange(val) {
      this.storeParameter.pageSize = val
      this.shopMethod()
    },
    checkedChange(item) {
      //多选框触发
      console.log(item)
      // this.setShop.id = item.id
      // this.setShop.status = item.bindStatus
      this.setShop.id = item.id
      this.setShop.status = 0
    },
    addMachine() {
      // 新曾设备
      this.dialogFormVisible = true
    },
    queryDetail(row) {
      //查看详情
      this.$router.push({
        name: 'MerchantQueryshop',
        params: { id: row.id },
      })
    },
  },
}
</script>

<style scoped lang="scss">
.all {
  height: auto;
  width: 97%;
  background-color: #fff;
  margin: 20px auto;
  margin-top: 15px;
  border-radius: 6px;
  padding: 15px;
  box-shadow: 0 0 4px 0 rgba(200, 200, 200, 0.5);
  padding-bottom: 40px;
}
.tagtable {
  background-color: #f2f2f6;
  border-radius: 6px;
  height: 70%;
  // padding: 15px;
  width: 100%;
}
.fy {
  text-align: right;
  margin-top: 10px;
}
::v-deep .el-form-item__label {
  padding: 0 !important;
}
.el-input--medium {
  width: 8vw !important;
}
::v-deep .el-dialog--center {
  border-radius: 5px !important;
}
.editMch {
  ::v-deep .el-form-item__content {
    display: inline-block !important;
  }
}
.dialogUnbundle {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  line-height: 40px;
}
::v-deep .el-dialog__body {
  padding: 10px 20px !important;
}
</style>
